package com.caipu.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caipu.common.Result;
import com.caipu.entity.Tag;
import com.caipu.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/admin/tag")
@CrossOrigin
public class AdminTagController {
    
    @Autowired
    private TagService tagService;
    
    @GetMapping("/list")
    public Result<Page<Tag>> list(@RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer size,
                                 @RequestParam(required = false) String keyword) {
        Page<Tag> pageObj = new Page<>(page, size);
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like("name", keyword);
        }
        
        queryWrapper.orderByDesc("create_time");
        Page<Tag> result = tagService.page(pageObj, queryWrapper);
        return Result.success(result);
    }
    
    @GetMapping("/all")
    public Result<List<Tag>> all() {
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        List<Tag> list = tagService.list(queryWrapper);
        return Result.success(list);
    }
    
    @GetMapping("/{id}")
    public Result<Tag> getById(@PathVariable Long id) {
        Tag tag = tagService.getById(id);
        return Result.success(tag);
    }
    
    @PostMapping
    public Result<Void> save(@RequestBody Tag tag) {
        tag.setCreateTime(LocalDateTime.now());
        tag.setUpdateTime(LocalDateTime.now());
        tag.setDeleted(0);
        
        boolean success = tagService.save(tag);
        return success ? Result.success() : Result.error("保存失败");
    }
    
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id, @RequestBody Tag tag) {
        tag.setId(id);
        tag.setUpdateTime(LocalDateTime.now());
        
        boolean success = tagService.updateById(tag);
        return success ? Result.success() : Result.error("更新失败");
    }
    
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        boolean success = tagService.removeById(id);
        return success ? Result.success() : Result.error("删除失败");
    }
}